<template>
  <UploadExcel :on-success="success" />
</template>

<script>
import { exportEmployeeAPI } from '@/api/employees'

export default {
  methods: {
    async success(data) {
      try {
        const newData = this.formatExcel(data)
        // console.log(newData)
        await exportEmployeeAPI(newData)
        this.$message.success('操作成功')
        this.$router.back()
      } catch (e) {
        this.$message.success(e)
        console.log(e)
      }
    },
    // 格式化excel
    formatExcel(data) {
      // 表头转换
      // newData.header = data.header.map(key_zh => this.zh2en(key_zh))
      // 数据转换
      return data.results.map(item => {
        const newItem = {}
        // 字段
        Object.keys(item).map(key_zh => {
          if (key_zh.indexOf('日期') !== -1) {
            return (newItem[this.zh2en(key_zh)] = new Date(
              this.formatDate(item[key_zh], '/')
            ))
          }
          newItem[this.zh2en(key_zh)] = item[key_zh]
        })
        return newItem
      })
    },
    // 格式化日期
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return (
        year +
        (month < 10 ? '0' + month : month) +
        (date < 10 ? '0' + date : date)
      )
    },
    // 中转英
    zh2en(str) {
      // 中转英字典
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }
      let key_en = ''
      Object.keys(userRelations).map(key_zh => {
        if (str === key_zh) key_en = userRelations[key_zh]
      })
      return key_en
    }
  }
}
</script>
